<template>
    <div class="administrative-division" v-if="navigationIndex === 1">
      <el-select @change="handleProvinceValueChange" style="width: 100%" size="small" v-model="value" placeholder="请选择省份" clearable>
        <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value">
        </el-option>
      </el-select>
      <div class="county-container">
        <div class="county-container-item" v-for="item in countyData" :key="item.code">
          <div @click="handleItemClick(item.value,'city')" class="sys-market">{{item.label}}</div>
          <div class="sys-county">
            <div @click="handleItemClick(item2.attributes.code,'county')" class="sys-county-item" v-for="item2 in item.children" :key="item2.attributes.code">{{item2.attributes.name}}</div>
          </div>
        </div>
      </div>
    </div>
</template>

<script>
import * as query from "@arcgis/core/rest/query.js"; // 地图查询
import Query from "@arcgis/core/rest/support/Query.js"; // 属性查询
import Graphic from "@arcgis/core/Graphic.js"; // 矢量表现

export default {
  name: "administrativeDivision",
  props:['navigationIndex'],
  data() {
    return {
      // 行政区划省数据
      options: [],
      value: '',
      // 行政区划市县数据
      countyData: [],
      graphic: '',
    }
  },
  watch: {
    navigationIndex: {
      handler(newVal,oldVal) {
        if (newVal === 1) {
          this.getProvinceData()
        }
      },
      immediate: true,
      deep: true
    }
  },
  mounted() {
    // 获取省级行政区划数据
    this.getProvinceData()
  },
  methods: {
    // 获取省级行政区划数据
    async getProvinceData() {
      let _that = this;
      let queryUrl = "https://services2.arcgis.com/NJdcylBy9exOSld0/arcgis/rest/services/economize_webMokaTuo/FeatureServer/0";
      // create the Query object
      let queryObject = new Query();
      // sql （1=1查询全部）
      queryObject.where = "1=1";
      // 是否返回地理数据（带有几何形状设置为true）
      queryObject.returnGeometry = false;
      // 可以指定返回的字段（* 号返回全部属性字段）
      queryObject.outFields = [ "*" ];
      // 请求数据
      let results = await query.executeQueryJSON(queryUrl, queryObject);
      let currentData = [];
      if (results.features.length > 0) {
        // 遍历行政区划省数据
        results.features.map( item => {
          currentData.push({
            value:item.attributes.code,
            label:item.attributes.name,
          })
        })
        _that.options = currentData;
        _that.countyData = [];
      }
    },
    // 触发下拉框选项
    async handleProvinceValueChange(value) {
      // 获取下级数据
      this.countyData = [];
      await this.getCityAndCountyDate(value)
    },
    // 获取下级市数据
    async getCityAndCountyDate(value) {
      let _that = this;
      let provinceCode = value.toString().substring(0,2)
      let queryUrl = "https://services2.arcgis.com/NJdcylBy9exOSld0/arcgis/rest/services/market_webMokaTuo/FeatureServer/0";
      // create the Query object
      let queryObject = new Query();
      // sql （1=1查询全部）
      queryObject.where = "code like '" + provinceCode + "%'";
      // 是否返回地理数据（带有几何形状设置为true）
      queryObject.returnGeometry = false;
      // 可以指定返回的字段（* 号返回全部属性字段）
      queryObject.outFields = [ "*" ];
      // 请求数据
      let results = await query.executeQueryJSON(queryUrl, queryObject);
      let currentData = [];
      if (results.features.length > 0) {
        // 遍历行政区划省数据
        results.features.map( item => {
          currentData.push({
            value:item.attributes.code,
            label:item.attributes.name,
          })
        })
        // 查找市下面的县
        for (const item2 of currentData) {
          let cityCode = item2.value.toString().substring(0,4)
          let queryUrl2 = "https://services2.arcgis.com/NJdcylBy9exOSld0/arcgis/rest/services/county_webMokaTuo/FeatureServer/0";
          // create the Query object
          let queryObject2 = new Query();
          // sql （1=1查询全部）
          queryObject2.where = "code like '" + cityCode + "%'";
          // 是否返回地理数据（带有几何形状设置为true）
          queryObject2.returnGeometry = false;
          // 可以指定返回的字段（* 号返回全部属性字段）
          queryObject2.outFields = [ "*" ];
          // 查询县数据
          let results2 = await query.executeQueryJSON(queryUrl2, queryObject2);
          if (results2.features.length > 0) {
            item2.children = results2.features
          }
        }
        // 行政区县市数据
        _that.countyData = [...currentData];
        console.log(_that.countyData);
      }
    },
    // 跳到行政区
    async handleItemClick(val,type) {
      let _that = this;
      let serverUrl = '';
      let code = '';
      if (type === 'city') {
        // 点击市级
        code = val.toString().substring(0,4);
        serverUrl = "https://services2.arcgis.com/NJdcylBy9exOSld0/arcgis/rest/services/market_webMokaTuo/FeatureServer/0";
      } else if(type === 'county') {
        // 点击县级
        code = val.toString().substring(0,6);
        serverUrl = "https://services2.arcgis.com/NJdcylBy9exOSld0/arcgis/rest/services/county_webMokaTuo/FeatureServer/0";
      }
      let queryObject = new Query();
      // sql （1=1查询全部）
      queryObject.where = "code like '" + code + "%'";
      // 是否返回地理数据（几何形状设置为true）
      queryObject.returnGeometry = true;
      // 可以指定返回的字段（* 号返回全部属性字段）
      queryObject.outFields = [ "*" ];
      queryObject.outSpatialReference = { wkid:4269  };
      // 请求数据
      let results = await query.executeQueryJSON(serverUrl,queryObject);
      // 渲染和定位
      const featuresResult = results.features[0];
      //屏幕上的坐标点 >>转成>> 地图上的经纬度
      // let mapPoint = {
      //   x: featuresResult.attributes.Shape__Area,
      //   y: featuresResult.attributes.Shape__Length,
      // }
      // const screenPoint = _that.$store.state.mapView.toMap(mapPoint);
      // 删除已有的 graphic
      if (_that.graphic) {
        _that.$store.state.mapView.graphics.remove(_that.graphic)
      }
      // 定义符号化渲染样式
      const fileSymbol = {
        // type = 'simple-fill', 'picture-fill', 'picture-marker', 'simple-line', 'simple-marker', 'text', 'label-3d', 'line-3d', 'mesh-3d', 'point-3d', 'polygon-3d', 'web-style', 'cim')
        type:'simple-fill',
        // 填充颜色
        color: [188, 240, 234, 0.1],
        outline: {
          width: 2,
          color: '#ffffff'
        }
      }
      // 几何图形表现
      _that.graphic = new Graphic({
        // geometry：几何
        geometry: featuresResult.geometry,
        // 样式
        symbol: fileSymbol,
      });
      // 添加到地图上
      _that.$store.state.mapView.graphics.add(_that.graphic)
      // 实现地图的跳转
      _that.$store.state.mapView.goTo({
        // 跳转的坐标
        center: [
          // 经度
          featuresResult.geometry.extent.center.longitude,
          // 纬度
          featuresResult.geometry.extent.center.latitude,
        ],
        // 地图缩放层级
        zoom:8
      })
    }
  }
}
</script>

<style scoped>
.administrative-division {
  position: absolute;
  top: 60px;
  right: 20px;
  width: 425px;
  min-height: 300px;
  max-height: 600px;
  overflow: auto;
  background: #ffffff;
  padding: 10px;
  box-sizing: border-box;
  cursor: pointer;
}
.county-container-item {
  font-size: 14px;
  color: #606266;
  margin: 5px 0;
  display: flex;
  align-items: center;
}
.sys-market {
  font-weight: bold;
  margin-right: 10px;
  padding: 5px 10px;
}
.sys-market:hover {
  background: #3C467C;
  color: #ffffff;
}
.sys-county {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  flex: 1;
}
.sys-county-item {
  padding: 5px 10px;
}
.sys-county-item:hover {
  background: #3C467C;
  color: #ffffff;
}
</style>